import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/welcome',
    component: () => import('@/views/Home'),
    children: [
      {
        path: 'welcome',
        name: 'Welcome',
        component: () => import('@/views/Welcome')
      },
      {
        path: 'users',
        name: 'User',
        component: () => import('../views/user/User.vue')
      },
      {
        path: 'roles',
        name: 'Roles',
        component: () => import('../views/rights/Roles.vue')
      },
      {
        path: 'rights',
        name: 'Rights',
        component: () => import('../views/rights/Rights.vue')
      },
      {
        path: 'goods',
        name: 'Goods',
        component: () => import('../views/goods/Goods.vue')
      },
      {
        path: '/add',
        name: 'Add',
        component: () => import('../views/goods/Add.vue')
      },
      {
        path: 'params',
        name: 'Params',
        component: () => import('../views/goods/Params.vue')
      },
      {
        path: 'categories',
        name: 'Categories',
        component: () => import('../views/goods/Categories.vue')
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('../views/orders/Orders.vue')
      },
      {
        path: 'reports',
        name: 'Reports',
        component: () => import('../views/reports/Reports.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login')
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.fullPath === '/login') {
    if (localStorage.getItem('token')) {
      next('/')
    } else {
      next()
    }
  } else {
    if (localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
